<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Request;
use think\Model;
use think\model\concern\SoftDelete;
use think\facade\Cache;
use app\common\model\AdminZavote as M;
use app\common\model\AdminZbuserinfo as MB;
use app\common\model\AdminZccandidate as MC;
use think\model\relation\HasOne;
use think\facade\Db;

class AdminZdvoter extends Model
{
    use SoftDelete;
     protected $deleteTime = false;

    // 获取列表
    public static function getList($biaoid)
    {
        $where = [];
        $limit = input('get.limit');
               //按名称查找
               if ($openid = input("openid")) {
                   $where[] = ["openid", "like",  $openid ];
               }
               //按编号查找
               if ($biaoid) {
                    $where[] = ["biaoid", "like",  $biaoid ];
                }
        $list = self::with(['gl','gl2'])->order('id','desc')->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }

    public function gl()
    {
        return $this->hasOne(AdminZbuserinfo::class,'uid','openid')->bind(['glopenid'=>'openid','glnickname'=>'nickname','glheadimgurl'=>'headimgurl']);
    }

    public function gl2()
    {
        return $this->hasOne(AdminZccandidate::class,'id','xiangid')->bind(['glname'=>'name']);
    }

    // 导出数据
    public static function goGetdata($biaoid)
    {
        $res = self::with(['gl','gl2'])->order('id','desc')->where('biaoid', $biaoid)->select();
        $restitle = M::where('id', $biaoid)->field('title')->find();
        return ['msg'=>'操作成功','code'=>200,'data'=>$res,'datatitle'=>$restitle];
    }  

    public static function ywgz($yonghuopenid,$voteid,$votezdlgzh){
        if($yonghuopenid==""){
            return 1;
        }
        $arrid = Cache::get('tpgettpbyidgzh:'.$voteid);
        if($arrid==""){
            $resgzh = Db::name('admin_zezhengzhpz')->where('appid',$votezdlgzh)->find();
            Cache::set('tpgettpbyidgzh:'.$voteid,$resgzh,310);
        } else {
            $resgzh = $arrid;
        }
        $appid = $resgzh['appid'];
        $appsecret = $resgzh['appsecret'];
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $access_msg = json_decode(file_get_contents($access_token));
        $token = $access_msg->access_token;
        $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$yonghuopenid."&lang=zh_CN";
        $subscribe = json_decode(file_get_contents($subscribe_msg));
        if(isset($subscribe->errcode)){
            return 2;
        }
        $gzxx = $subscribe->subscribe;
        if($gzxx === 0){
            return 3;
        }
        if($gzxx === 1){
            return 4;
        }
    }
    
    // 单选投票
    public static function danxtp($biaoid,$xuanshouid,$zuming,$wxid,$yonghuid,$yonghuopenid)
    {
        //根据表id查出所有表的需求
        //$vote = M::find($biaoid);

        $arrid = Cache::get('tpgettpbyid:'.$biaoid);
        if($arrid==""){
            $vote = M::find($biaoid);
            Cache::set('tpgettpbyid:'.$biaoid,$vote,310);
        } else {
            $vote = $arrid;
        }

        $nowtime = time();
        $time2todayywgz = strtotime(date('Y-m-d',strtotime('+1 day')));  //  今日结束时间 23:59戳

        if ($vote['danxuan'] != 0) {die;}
        if ($vote['isguanzhu'] == 1) {
            $yonghuywgz = Cache::get('tpyonghuywgz:'.$biaoid.$yonghuid);
            if($yonghuywgz==""){
                //$zdvoter = new AdminZdvoter;
                //$a = $zdvoter->ywgz($yonghuopenid,$vote['id'],$vote['zdlgzh']);
                $headerarr = array('yonghuopenid:'.$yonghuopenid,'voteid:'.$vote['id'],'votezdlgzh:'.$vote['zdlgzh']);
                // $url = 'http://thtpadmin.diandianx.com/index/api/ywgz';
                $url = 'http://thtpadmin.xingtaiwang.net/index/api/ywgz';
                $a = https_request($url, null, $headerarr);
                if($a=="1"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>503,'message'=>'openid错误','openid'=>$yonghuopenid,'__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="2"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>503,'message'=>'openid错误','openid'=>$yonghuopenid,'__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="3"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>502,'message'=>'未关注','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="4"){
                    $reszywgz = 0;
                    $cookieshijian = $time2todayywgz - $nowtime;//存cookie时间  秒
                    Cache::set('tpyonghuywgz:'.$biaoid.$yonghuid,$reszywgz,$cookieshijian);
                }
            }
        }
        
        //判断投票时间
        if ($nowtime<strtotime($vote['begintime'])) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>101,'message'=>'未开始','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }elseif($nowtime>strtotime($vote['stoptime'])) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>102,'message'=>'已结束','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }

        //判断投票时间
        if (date("H:i:s",time())>$vote['toutime']  &&  date("H:i:s",time())<$vote['notoutime']) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>103,'message'=>'该时间段暂停中','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }

        //$candidate = MC::find($xuanshouid);

        $arrid = Cache::get('tpgettpoptionbypid:'.$xuanshouid);
        if($arrid==""){
            $candidate = MC::find($xuanshouid);
            Cache::set('tpgettpoptionbypid:'.$xuanshouid,$candidate,310);
        } else {
            $candidate = $arrid;
        }

        // if($candidate['ztdp'] == 0){
        //     //暂停投票处理
        //     $t1 = $nowtime-$vote['shijian']*60;
                    
        //     $dataxin = self::order('id','desc')->where('xiangid','=',$xuanshouid)->where([
        //         ['datetime','>',$t1],
        //         ['datetime','<',$nowtime]
        //     ])->sum('cishu');

        //     if ($dataxin>=$vote['piaoshu']) {
        //         MC::where('id', $xuanshouid)->update(['ztdp' => '1']);
        //     }
        // }elseif($candidate['ztdp'] == 1){
        //     $t2 = $nowtime-$vote['fenzhongshu']*60;

        //     $dataxin = self::order('id','desc')->where('xiangid','=',$xuanshouid)->where([
        //         ['datetime','>',$t2],
        //         ['datetime','<',$nowtime]
        //     ])->sum('cishu');

        //     if ($dataxin==0) {
        //         MC::where('id', $xuanshouid)->update(['ztdp' => '0']);
        //     }
        // }

        if ($candidate['ztdp'] == 1) {
            //暂停得票
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>104,'message'=>'暂停得票','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }

        if ($vote['numgzh'] == 1) {
            if($wxid != 1){
                die;
            }
        }elseif($vote['numgzh'] == 2){
            if($wxid != 1 && $wxid != 2){
                die;
            }
        }elseif($vote['numgzh'] == 3){
            if($wxid != 1 && $wxid != 2 && $wxid != 3){
                die;
            }
        }elseif($vote['numgzh'] == 4){
            if($wxid != 1 && $wxid != 2 && $wxid != 3 && $wxid != 4){
                die;
            }
        }elseif($vote['numgzh'] == 5){
            if($wxid != 1 && $wxid != 2 && $wxid != 3 && $wxid != 4 && $wxid != 5){
                die;
            }
        }else{
            die;
        }

        if($vote['cishu']==0){
            $timetoday = strtotime(date("Y-m-d",time()));   //今日00时间戳
            $time2today = strtotime(date('Y-m-d',strtotime('+1 day')));  //  今日结束时间 23:59戳

            // $wz['biaoid']=$biaoid;
            // $wz['openid']=$yonghuid;
            // $resz = self::order('id','desc')->where($wz)->where([
            //     ['datetime','>',$timetoday],
            //     ['datetime','<',$time2today]
            // ])->sum('cishu');
            
            // $yonghutousum = Cache::get('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);
            $yonghutousum = Cache::store('redis')->get('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);



            if($yonghutousum==""){
                $resz = 0;
                $cookieshijian = $time2today - $nowtime;//存cookie时间  秒
                // Cache::tag('tpyonghutousum')->set('tpyonghutousum:'.$biaoid.$yonghuid.$wxid,$resz,$cookieshijian);
                Cache::store('redis')->tag('tpyonghutousum')->set('tpyonghutousum:'.$biaoid.$yonghuid.$wxid,$resz,$cookieshijian);



            } else {
                $resz = $yonghutousum;
            }

            if($resz >= $vote['daycishu']){
                //大于今日投票次数，返回票数已投完，请明日再来！
                $token = request()->buildToken('__token__', 'sha1');
                $data=['code'=>205,'message'=>'票数已投完，请明日再来','__token__'=>$token];
                return ['code'=>200,'message'=>'成功','data'=>$data];
            }

            if($zuming){
                $yonghutouzusum = Cache::get('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                if($yonghutouzusum==""){
                    $reszzu = 0;
                    $cookieshijianzu = $time2today - $nowtime;//存cookie时间  秒
                    Cache::tag('tpyonghutouzusum')->set('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming,$reszzu,$cookieshijianzu);
                } else {
                    $reszzu = $yonghutouzusum;
                }
                if($reszzu >= $vote['fenzupiao']){
                    //大于今日投票次数，返回票数已投完，请明日再来！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>527,'message'=>'请投其他组别','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }

            $w['biaoid']=$biaoid;
            $w['xiangid']=$xuanshouid;
            $w['openid']=$yonghuid;
            $w['wxid']=$wxid;
            $res = self::order('id','desc')->where($w)->where([
                ['datetime','>',$timetoday],
                ['datetime','<',$time2today]
            ])->find();
            if($res){
                if($res['cishu'] >= $vote['daypiao']){
                    //大于该选手得票次数，返回请投其他候选！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>107,'message'=>'请投其他候选','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                M::where('id', $biaoid)->inc('sumpiao',1)->update();
                if($vote['todaytime'] == date("Y-m-d",time())){
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }
                
                //对应的numpiao和zhennumpiao加1
                MC::where('id', $xuanshouid)->inc('numpiao',1)->update();
                MC::where('id', $xuanshouid)->inc('zhennumpiao',1)->update();
                $db=self::where('id', $res['id'])->inc('cishu',1)->update();
                if($db){
                    // Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($wxid){
                        // Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);
                        Cache::store('redis')->inc('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);



                    }else{
                        Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    }
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }
                    
                    //$num=MC::where('id', $xuanshouid)->find();
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }else{
                M::where('id', $biaoid)->inc('sumpiao',1)->update();
                if($vote['todaytime'] == date("Y-m-d",time())){
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }
                
                //对应的numpiao和zhennumpiao加1
                MC::where('id', $xuanshouid)->inc('numpiao',1)->update();
                MC::where('id', $xuanshouid)->inc('zhennumpiao',1)->update();
                
                // 进行插入数据
                $data['biaoid'] = $biaoid;
                $data['xiangid'] = $xuanshouid;
                if($zuming){
                    $data['zuming'] = $zuming;
                }
                if($wxid){
                    $data['wxid'] = $wxid;
                }
                $data['openid'] = $yonghuid;
                $data['datetime'] = $nowtime;
                $data['cishu'] = '1';
                $data['riqi'] = date("Y-m-d",time());
                $data['ip'] =  getip();
                $db=self::create($data);
                if($db){
                    // Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($wxid){
                        // Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);
                        Cache::store('redis')->inc('tpyonghutousum:'.$biaoid.$yonghuid.$wxid);



                    }else{
                        Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    }
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }
                    
                    //$num=MC::where('id', $xuanshouid)->find();
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }
        }elseif($vote['cishu']==1){
            // $wz['biaoid']=$biaoid;
            // $wz['openid']=$yonghuid;
            // $resz = self::order('id','desc')->where($wz)->sum('cishu');

            $yonghutousum = Cache::get('tpyonghutousum:'.$biaoid.$yonghuid);
            if($yonghutousum==""){
                $resz = 0;
                $time2todayjieshu = strtotime($vote['stoptime']);
                $cookieshijian = $time2todayjieshu - $nowtime;//存cookie时间  秒
                Cache::tag('tpyonghutousum')->set('tpyonghutousum:'.$biaoid.$yonghuid,$resz,$cookieshijian);
            } else {
                $resz = $yonghutousum;
            }

            if($resz >= $vote['daycishu']){
                //大于投票总次数，返回票数已投完！
                $token = request()->buildToken('__token__', 'sha1');
                $data=['code'=>105,'message'=>'票数已投完','__token__'=>$token];
                return ['code'=>200,'message'=>'成功','data'=>$data];
            }

            if($zuming){
                $yonghutouzusum = Cache::get('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                if($yonghutouzusum==""){
                    $reszzu = 0;
                    $time2todayjieshuzu = strtotime($vote['stoptime']);
                    $cookieshijianzu = $time2todayjieshuzu - $nowtime;//存cookie时间  秒
                    Cache::tag('tpyonghutouzusum')->set('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming,$reszzu,$cookieshijianzu);
                } else {
                    $reszzu = $yonghutouzusum;
                }
                if($reszzu >= $vote['fenzupiao']){
                    //大于今日投票次数，返回票数已投完，请明日再来！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>527,'message'=>'请投其他组别','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }

            $w['biaoid']=$biaoid;
            $w['xiangid']=$xuanshouid;
            $w['openid']=$yonghuid;
            $res = self::order('id','desc')->where($w)->find();
            if($res){
                if($res['cishu'] >= $vote['daypiao']){
                    //大于该选手得票次数，返回请投其他候选！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>107,'message'=>'请投其他候选','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                M::where('id', $biaoid)->inc('sumpiao',1)->update();
                if($vote['todaytime'] == date("Y-m-d",time())){
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }

                //对应的numpiao和zhennumpiao加1
                MC::where('id', $xuanshouid)->inc('numpiao',1)->update();
                MC::where('id', $xuanshouid)->inc('zhennumpiao',1)->update();
                $db=self::where('id', $res['id'])->inc('cishu',1)->update();
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }
                    
                    //$num=MC::where('id', $xuanshouid)->find();
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }else{
                M::where('id', $biaoid)->inc('sumpiao',1)->update();
                if($vote['todaytime'] == date("Y-m-d",time())){
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    M::where('id', $biaoid)->inc('todaypiao',1)->update();
                }
                
                //对应的numpiao和zhennumpiao加1
                MC::where('id', $xuanshouid)->inc('numpiao',1)->update();
                MC::where('id', $xuanshouid)->inc('zhennumpiao',1)->update();
                
                // 进行插入数据
                $data['biaoid'] = $biaoid;
                $data['xiangid'] = $xuanshouid;
                if($zuming){
                    $data['zuming'] = $zuming;
                }
                $data['openid'] = $yonghuid;
                $data['datetime'] = $nowtime;
                $data['cishu'] = '1';
                $data['riqi'] = date("Y-m-d",time());
                $data['ip'] =  getip();
                $db=self::create($data);
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }
                    
                    //$num=MC::where('id', $xuanshouid)->find();
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }
        }
    }

    // 多选投票
    public static function duoxtp($biaoid,$xuanshouid,$zuming,$yonghuid,$yonghuopenid)
    {
        $xuanshouidstr = rtrim($xuanshouid, ',');
        $xuanshouidarr = explode(",", $xuanshouidstr); //把字符串打散为数组
        
        //根据表id查出所有表的需求
        //$vote = M::find($biaoid);

        $arrid = Cache::get('tpgettpbyid:'.$biaoid);
        if($arrid==""){
            $vote = M::find($biaoid);
            Cache::set('tpgettpbyid:'.$biaoid,$vote,310);
        } else {
            $vote = $arrid;
        }

        $nowtime = time();
        $time2todayywgz = strtotime(date('Y-m-d',strtotime('+1 day')));  //  今日结束时间 23:59戳
        
        if ($vote['danxuan'] != 1) {die;}
        if ($vote['isguanzhu'] == 1) {
            $yonghuywgz = Cache::get('tpyonghuywgz:'.$biaoid.$yonghuid);
            if($yonghuywgz==""){
                //$zdvoter = new AdminZdvoter;
                //$a = $zdvoter->ywgz($yonghuopenid,$vote['id'],$vote['zdlgzh']);
                $headerarr = array('yonghuopenid:'.$yonghuopenid,'voteid:'.$vote['id'],'votezdlgzh:'.$vote['zdlgzh']);
                // $url = 'http://thtpadmin.diandianx.com/index/api/ywgz';
                $url = 'http://thtpadmin.xingtaiwang.net/index/api/ywgz';
                $a = https_request($url, null, $headerarr);
                if($a=="1"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>503,'message'=>'openid错误','openid'=>$yonghuopenid,'__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="2"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>503,'message'=>'openid错误','openid'=>$yonghuopenid,'__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="3"){
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>502,'message'=>'未关注','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
                if($a=="4"){
                    $reszywgz = 0;
                    $cookieshijian = $time2todayywgz - $nowtime;//存cookie时间  秒
                    Cache::set('tpyonghuywgz:'.$biaoid.$yonghuid,$reszywgz,$cookieshijian);
                }
            }
        }

        $xuanshouidarrnum = count($xuanshouidarr);
        if($xuanshouidarrnum < $vote['minxuan']){
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>301,'message'=>'选少了','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }elseif($xuanshouidarrnum > $vote['maxxuan']){
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>401,'message'=>'选多了','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }
        
        //判断投票时间
        if ($nowtime<strtotime($vote['begintime'])) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>101,'message'=>'未开始','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }elseif($nowtime>strtotime($vote['stoptime'])) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>102,'message'=>'已结束','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }

        //判断投票时间
        if (date("H:i:s",time())>$vote['toutime']  &&  date("H:i:s",time())<$vote['notoutime']) {
            $token = request()->buildToken('__token__', 'sha1');
            $data=['code'=>103,'message'=>'该时间段暂停中','__token__'=>$token];
            return ['code'=>200,'message'=>'成功','data'=>$data];
        }

        if($vote['cishu']==0){
            $timetoday = strtotime(date("Y-m-d",time()));   //今日00时间戳
            $time2today = strtotime(date('Y-m-d',strtotime('+1 day')));  //  今日结束时间 23:59戳

            // $wz['biaoid']=$biaoid;
            // $wz['openid']=$yonghuid;
            // $resz = self::order('id','desc')->where($wz)->where([
            //     ['datetime','>',$timetoday],
            //     ['datetime','<',$time2today]
            // ])->sum('cishu');

            $yonghutousum = Cache::get('tpyonghutousum:'.$biaoid.$yonghuid);
            if($yonghutousum==""){
                $resz = 0;
                $cookieshijian = $time2today - $nowtime;//存cookie时间  秒
                Cache::tag('tpyonghutousum')->set('tpyonghutousum:'.$biaoid.$yonghuid,$resz,$cookieshijian);
            } else {
                $resz = $yonghutousum;
            }

            if($resz >= $vote['daycishu']){
                //大于今日投票次数，返回票数已投完，请明日再来！
                $token = request()->buildToken('__token__', 'sha1');
                $data=['code'=>205,'message'=>'票数已投完，请明日再来','__token__'=>$token];
                return ['code'=>200,'message'=>'成功','data'=>$data];
            }

            if($zuming){
                $yonghutouzusum = Cache::get('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                if($yonghutouzusum==""){
                    $reszzu = 0;
                    $cookieshijianzu = $time2today - $nowtime;//存cookie时间  秒
                    Cache::tag('tpyonghutouzusum')->set('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming,$reszzu,$cookieshijianzu);
                } else {
                    $reszzu = $yonghutouzusum;
                }
                if($reszzu >= $vote['fenzupiao']){
                    //大于今日投票次数，返回票数已投完，请明日再来！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>527,'message'=>'请投其他组别','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }

            $w['biaoid']=$biaoid;
            $w['xiangid']=$xuanshouidstr;
            $w['openid']=$yonghuid;
            $res = self::order('id','desc')->where($w)->where([
                ['datetime','>',$timetoday],
                ['datetime','<',$time2today]
            ])->find();
            if($res){
                // foreach ($xuanshouidarr as $k => $v) {
                //     M::where('id', $biaoid)->inc('sumpiao',1)->update();
                // }
                
                M::where('id', $biaoid)->inc('sumpiao',$xuanshouidarrnum)->update();

                if($vote['todaytime'] == date("Y-m-d",time())){
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }

                // foreach ($xuanshouidarr as $k => $v) {
                //     //对应的numpiao和zhennumpiao加1
                //     MC::where('id', $v)->inc('numpiao',1)->update();
                //     MC::where('id', $v)->inc('zhennumpiao',1)->update();
                // }

                MC::whereIn('id', $xuanshouidstr)->inc('numpiao')->update();
                MC::whereIn('id', $xuanshouidstr)->inc('zhennumpiao')->update();

                // $user = new AdminZccandidate;
                // $list = [];
                // foreach ($xuanshouidarr as $k => $v) {
                //     $list[] = [
                //         ['id'=>$v, 'numpiao'=>'numpiao'+1],
                //         ['id'=>$v, 'zhennumpiao'=>'zhennumpiao'+1]
                //     ];
                // }
                // $user->saveAll($list);

                $db=self::where('id', $res['id'])->inc('cishu',1)->update();
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }

                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }else{
                // foreach ($xuanshouidarr as $k => $v) {
                //     M::where('id', $biaoid)->inc('sumpiao',1)->update();
                // }

                M::where('id', $biaoid)->inc('sumpiao',$xuanshouidarrnum)->update();
                
                if($vote['todaytime'] == date("Y-m-d",time())){
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }
                
                // foreach ($xuanshouidarr as $k => $v) {
                //     //对应的numpiao和zhennumpiao加1
                //     MC::where('id', $v)->inc('numpiao',1)->update();
                //     MC::where('id', $v)->inc('zhennumpiao',1)->update();
                // }

                MC::whereIn('id', $xuanshouidstr)->inc('numpiao')->update();
                MC::whereIn('id', $xuanshouidstr)->inc('zhennumpiao')->update();

                // $user = new AdminZccandidate;
                // $list = [];
                // foreach ($xuanshouidarr as $k => $v) {
                //     $list[] = [
                //         ['id'=>$v, 'numpiao'=>'numpiao'+1],
                //         ['id'=>$v, 'zhennumpiao'=>'zhennumpiao'+1]
                //     ];
                // }
                // $user->saveAll($list);
                
                // 进行插入数据
                $data['biaoid'] = $biaoid;
                $data['xiangid'] = $xuanshouidstr;
                if($zuming){
                    $data['zuming'] = $zuming;
                }
                $data['openid'] = $yonghuid;
                $data['datetime'] = $nowtime;
                $data['cishu'] = '1';
                $data['riqi'] = date("Y-m-d",time());
                $data['ip'] =  getip();
                $db=self::create($data);
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }

                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }
        }elseif($vote['cishu']==1){
            // $wz['biaoid']=$biaoid;
            // $wz['openid']=$yonghuid;
            // $resz = self::order('id','desc')->where($wz)->sum('cishu');

            $yonghutousum = Cache::get('tpyonghutousum:'.$biaoid.$yonghuid);
            if($yonghutousum==""){
                $resz = 0;
                $time2todayjieshu = strtotime($vote['stoptime']);
                $cookieshijian = $time2todayjieshu - $nowtime;//存cookie时间  秒
                Cache::tag('tpyonghutousum')->set('tpyonghutousum:'.$biaoid.$yonghuid,$resz,$cookieshijian);
            } else {
                $resz = $yonghutousum;
            }

            if($resz >= $vote['daycishu']){
                //大于投票总次数，返回票数已投完！
                $token = request()->buildToken('__token__', 'sha1');
                $data=['code'=>105,'message'=>'票数已投完','__token__'=>$token];
                return ['code'=>200,'message'=>'成功','data'=>$data];
            }

            if($zuming){
                $yonghutouzusum = Cache::get('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                if($yonghutouzusum==""){
                    $reszzu = 0;
                    $time2todayjieshuzu = strtotime($vote['stoptime']);
                    $cookieshijianzu = $time2todayjieshuzu - $nowtime;//存cookie时间  秒
                    Cache::tag('tpyonghutouzusum')->set('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming,$reszzu,$cookieshijianzu);
                } else {
                    $reszzu = $yonghutouzusum;
                }
                if($reszzu >= $vote['fenzupiao']){
                    //大于今日投票次数，返回票数已投完，请明日再来！
                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>527,'message'=>'请投其他组别','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }

            $w['biaoid']=$biaoid;
            $w['xiangid']=$xuanshouidstr;
            $w['openid']=$yonghuid;
            $res = self::order('id','desc')->where($w)->find();
            if($res){
                // foreach ($xuanshouidarr as $k => $v) {
                //     M::where('id', $biaoid)->inc('sumpiao',1)->update();
                // }

                M::where('id', $biaoid)->inc('sumpiao',$xuanshouidarrnum)->update();

                if($vote['todaytime'] == date("Y-m-d",time())){
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }

                // foreach ($xuanshouidarr as $k => $v) {
                //     //对应的numpiao和zhennumpiao加1
                //     MC::where('id', $v)->inc('numpiao',1)->update();
                //     MC::where('id', $v)->inc('zhennumpiao',1)->update();
                // }

                MC::whereIn('id', $xuanshouidstr)->inc('numpiao')->update();
                MC::whereIn('id', $xuanshouidstr)->inc('zhennumpiao')->update();

                $db=self::where('id', $res['id'])->inc('cishu',1)->update();
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }

                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }else{
                // foreach ($xuanshouidarr as $k => $v) {
                //     M::where('id', $biaoid)->inc('sumpiao',1)->update();
                // }

                M::where('id', $biaoid)->inc('sumpiao',$xuanshouidarrnum)->update();
                
                if($vote['todaytime'] == date("Y-m-d",time())){
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }else{
                    if(!file_exists("./toupiaojilu/".$biaoid))//文件夹不存在，先生成文件夹
                    {
                        mkdir("./toupiaojilu/".$biaoid,755,true);
                    }
                    $f = fopen ( "./toupiaojilu/".$biaoid."/toupiaojilu.txt","a");
                    fwrite($f,$vote['todaytime'].'|'.$vote['todaypiao'].','."\n");
                    fclose($f);
                    M::where('id', $biaoid)->update(['todaypiao' => '0']);
                    M::where('id', $biaoid)->update(['todaytime' => date("Y-m-d",time())]);
                    // foreach ($xuanshouidarr as $k => $v) {
                    //     M::where('id', $biaoid)->inc('todaypiao',1)->update();
                    // }

                    M::where('id', $biaoid)->inc('todaypiao',$xuanshouidarrnum)->update();
                }
                
                // foreach ($xuanshouidarr as $k => $v) {
                //     //对应的numpiao和zhennumpiao加1
                //     MC::where('id', $v)->inc('numpiao',1)->update();
                //     MC::where('id', $v)->inc('zhennumpiao',1)->update();
                // }
                
                MC::whereIn('id', $xuanshouidstr)->inc('numpiao')->update();
                MC::whereIn('id', $xuanshouidstr)->inc('zhennumpiao')->update();
                
                // 进行插入数据
                $data['biaoid'] = $biaoid;
                $data['xiangid'] = $xuanshouidstr;
                if($zuming){
                    $data['zuming'] = $zuming;
                }
                $data['openid'] = $yonghuid;
                $data['datetime'] = $nowtime;
                $data['cishu'] = '1';
                $data['riqi'] = date("Y-m-d",time());
                $data['ip'] =  getip();
                $db=self::create($data);
                if($db){
                    Cache::inc('tpyonghutousum:'.$biaoid.$yonghuid);
                    if($zuming){
                        Cache::inc('tpyonghutouzusum:'.$biaoid.$yonghuid.$zuming);
                    }

                    $token = request()->buildToken('__token__', 'sha1');
                    $data=['code'=>106,'message'=>'票数成功','__token__'=>$token];
                    return ['code'=>200,'message'=>'成功','data'=>$data];
                }
            }
        }
    }
}
